const util = require('../../utils/util.js')

let playTimeInterval
let recordTimeInterval

Page({
  onShareAppMessage() {
    return {
      title: '录音',
      path: '../voice/voice'
    }
  },

  data: {
    uid: '',
    phone: '',
    step: 1,
    numberToRead: '',
    sessionId: '',
    tempFilePath: '',
    recording: false,
    playing: false,
    hasRecord: false,
    recordTime: 0,
    playTime: 0,
    formatedRecordTime: '00:00:00',
    formatedPlayTime: '00:00:00'
  },
  onHide: function(options) {

    var tempStep = wx.getStorageSync('step');
    console.log('onHide中的step为' + tempStep);

    if (tempStep > 3) {
      console.log('onHide中执行跳转的step为' + tempStep);

      wx.setStorageSync('step', 1)
      wx.redirectTo({
        url: '../index/index'
      })
    }

  },
  onLoad: function(options) {

    // this.setData({
    //   uid: options.phone
    // }) 

    this.data.phone = wx.getStorageSync('phone');
    var tempStep = wx.getStorageSync('step');
    console.log('onLoad中的step为' + tempStep);

    if (tempStep > 3) {
      console.log('onLoad中执行跳转的step为' + tempStep);

      wx.setStorageSync('step', 1)

      wx.redirectTo({
        url: '../index/index'
      })
    }

    if (tempStep) {
      this.setData({
        phone: this.data.phone,
        step: tempStep
      })
    } else {
      this.setData({
        phone: this.data.phone
      })
    }

    var that = this;
    wx.request({
      url: 'https://aqhy.citydo.com.cn/safe/mini/getToken',
      method: 'POST',

      success: function(res) {

        if (res.data.code == 0) {

          var data = res.data
          var code = res.data.code
          var numberToRead = res.data.data.token
          var sessionId = res.data.data.sessionId

          that.setData({
            numberToRead: res.data.data.token,
            sessionId: res.data.data.sessionId
          })

        } else {
          wx.showModal({
            title: '提示',
            content: res.data.msg
          })
        }

      },
      fail: function(res) {
        console.log(res);
      }
    })
  },

  onHide() {

    if (this.data.playing) {
      this.stopVoice()
    } else if (this.data.recording) {
      this.stopRecordUnexpectedly()
    }
  },

  startRecord() {
    this.setData({
      recording: true
    })

    const that = this
    recordTimeInterval = setInterval(function() {
      const recordTime = that.data.recordTime += 1
      that.setData({
        formatedRecordTime: util.formatTime(that.data.recordTime),
        recordTime
      })
    }, 1000)
    console.log('外部startRecord的tempFilePath为' + this.data.tempFilePath);

    wx.startRecord({
      success(res) {
        console.log('wx.startRecord的tempFilePath为' + res.tempFilePath);

        that.setData({
          hasRecord: true,
          tempFilePath: res.tempFilePath,
          formatedPlayTime: util.formatTime(that.data.playTime)
        })

        that.upload();
      },
      complete() {
        that.setData({
          recording: false
        })
        clearInterval(recordTimeInterval)
      }
    })
  },

  stopRecord() {
    console.log('stopRecord的tempFilePath为' + this.data.tempFilePath);
    wx.stopRecord()

  },

  stopRecordUnexpectedly() {
    console.log('stopRecordUnexpectedly的tempFilePath为' + this.data.tempFilePath);
    const that = this
    wx.stopRecord({
      success() {
        console.log('stop record success')
        clearInterval(recordTimeInterval)
        that.setData({
          recording: false,
          hasRecord: false,
          recordTime: 0,
          formatedRecordTime: util.formatTime(0)
        })
      }
    })
  },

//上传文件
  upload(res) {
    wx.showLoading({
      title: '录音上传中',
    })
    console.log('upload的tempFilePath为' + this.data.tempFilePath);

    var tempFilePath = this.data.tempFilePath;
    var phone = this.data.phone;
    var stepOne = this.data.step;
    console.log('upload中尚未调用uploadFilestep为' + stepOne);

    wx.uploadFile({

      url: "https://aqhy.citydo.com.cn/safe/mini/uploadAndRegisterVoice",
      // url: "http://172.16.16.110:8180/safe/mini/uploadAndRegisterVoice",
      filePath: tempFilePath,
      name: "file",
      method: 'POST',
      header: {

        'Content-Type': 'multipart/form-data'
        // ,
        // APIKEY: authData["APIKEY"],
        // timestamp: authData["timestamp"],
        // nonce: authData["nonce"],
        // signature: authData["signature"],
        // APISECRET: authData["api_secret"]
      },
      formData: {
        phone: phone,
        step: stepOne
      },
      success: function(res) {
        wx.hideLoading();
        var data = res.data
        res = JSON.parse(res.data)
        if (res.code == 0) {

          console.info(res.msg)

          // this.data.step = this.data.step + 1

          wx.showModal({
            title: '提示',
            content: '第' + stepOne + '次验证成功',
            showCancel: false, //是否显示取消按钮

            success: function(res) {
              // wx.setStorageSync("phone", res.data)
              if (res.cancel) {
                //点击取消,默认隐藏弹框
              } else {
                //点击确定
                stepOne = stepOne + 1

                wx.setStorageSync('step', stepOne)

                console.log('uploadFile中成功的step为' + stepOne);

                if (stepOne > 3) {
                  wx.setStorageSync('step', 1)

                  wx.showModal({
                    title: '提示',
                    content: '音频注册成功'
                  })
                  console.log('uploadFile中成功执行跳转的step为' + stepOne);
                  wx.redirectTo({
                    url: '../index/index'
                  })

                  return;
                }
                console.log('uploadFile中成功执行registervoice跳转的step为' + stepOne);

                wx.redirectTo({
                  url: '../registervoice/registervoice?step=' + stepOne
                })

              }
            },
            fail: function(res) {}, //接口调用失败的回调函数
            complete: function(res) {

            }, //接口调用结束的回调函数（调用成功、失败都会

          })

        } else {

          if (res.code == 600) {

            wx.showModal({
              title: '提示',
              content: res.msg,
              showCancel: false,
              success: function(res) {

                wx.redirectTo({
                  url: '../index/index'
                })

              }
            })
            return;
          }

          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false, //是否显示取消按钮
            success: function(res) {
              console.log('uploadFile中失败的step为' + stepOne);
              stepOne = stepOne + 1
              wx.setStorageSync('step', stepOne)

              if (stepOne > 3) {
                wx.setStorageSync('step', 1)

                wx.showModal({
                  title: '提示',
                  content: '音频注册失败'
                })

                console.log('uploadFile中失败执行跳转的step为' + stepOne);

                wx.redirectTo({
                  url: '../index/index'
                })

                return;
              }
              // wx.setStorageSync("phone", res.data)
              if (res.cancel) {
                //点击取消,默认隐藏弹框
              } else {
                //点击确定
                console.log('uploadFile中失败了继续执行registervoice的step为' + stepOne);

                wx.redirectTo({
                  url: '../registervoice/registervoice?step='
                })
              }
            },
            fail: function(res) {}, //接口调用失败的回调函数
            complete: function(res) {}, //接口调用结束的回调函数（调用成功、失败都会
          })
        }
      },
      fail: function() {
        wx.showModal({
          title: '提示',
          content: res.msg
        })
      }
      // ,
      // complete: () => {
      //   wx.showModal({
      //     title: '提示',
      //     content: '音频上传完成'
      //   })

      // }

    })
  }
})